package com.example.mysafegarud;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.icu.text.NumberFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;

public class HomeActivity extends AppCompatActivity {

    private TextView textVersion;
    private ViewHolderBar viewHolderBar;
    private AlertDialog alertDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        //获取权限状态
        int checkSelfPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        //判断权限是否获取
        if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
            //请求权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
        }
        initView();
    }

    private void initView() {
        textVersion = (TextView) findViewById(R.id.textVersion);
        ifup("http://hhdev.cn/updateinfo.html");
    }

    /**
     * 检测版本状态
     *
     * @param url 查询最新版本号接口
     */
    private void ifup(String url) {
        RequestParams params = new RequestParams(url);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Enty enty = new Gson().fromJson(result, Enty.class);
                int code = enty.getCode();
                String apkurl = enty.getApkurl();
                String des = enty.getDes();
                Toast.makeText(x.app(), code+"" , Toast.LENGTH_LONG).show();
                if (code > BuildConfig.VERSION_CODE) {
                    win(HomeActivity.this, apkurl,code,des);
                } else {
                    into();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 跳转至主界面
     */
    private void into() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        startActivity(new Intent(HomeActivity.this, MainActivity.class));
                    }
                });
            }
        }).start();
    }

    /**
     * APK下载进度弹窗
     *
     * @param context 上下文
     *
     */
    private void winBar(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate(R.layout.layout3, null);
        viewHolderBar = new ViewHolderBar(view);
        builder.setView(view);
        builder.setTitle("正在下载......");;
        builder.setIcon(R.drawable.h046);
        builder.setCancelable(false);
        alertDialog = builder.create();
        alertDialog.show();
        alertDialog.setCancelable(false);
    }

    /**
     * 提示更新APK弹窗
     *
     * @param context 上下文
     * @param apkUrl  下载地址
     */
    private void win(final Context context, final String apkUrl,int code,String des) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("检查到新版本："+(double)code);
        builder.setMessage("\n"+des);
        builder.setCancelable(false);
        builder.setIcon(R.drawable.h046);
        builder.setPositiveButton("立即升级", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                loadNewVersion(context,apkUrl);
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("暂不升级", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                        into();
                        dialog.dismiss();
            }
        });
        builder.show();

    }

    /**
     * 下载、更新APK
     *
     * @param apkUrl 下载地址
     */
    private void loadNewVersion(final Context context, String apkUrl) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            NumberFormat numberFormat = NumberFormat.getPercentInstance();
            numberFormat.setMinimumFractionDigits(2);
        }
        winBar(context);
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
        OkGo.<File>get(apkUrl)//
                .tag(this)//
                .execute(new FileCallback() {
                    @Override
                    public void onStart(Request<File, ? extends Request> request) {
                    }

                    @Override
                    public void onSuccess(Response<File> response) {
                        alertDialog.dismiss();
                        //getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
                        installApk(HomeActivity.this, response.body().getName());
                        finish();
                    }

                    @Override
                    public void onError(Response<File> response) {
                    }

                    @Override
                    public void downloadProgress(Progress progres) {
                        String downloadLength = Formatter.formatFileSize(getApplicationContext(), progres.currentSize);//获取的文件大小
                        String totalLength = Formatter.formatFileSize(getApplicationContext(), progres.totalSize);//总文件大小
                        String speed = Formatter.formatFileSize(getApplicationContext(), progres.speed);//速度
                        viewHolderBar.textSize.setText(downloadLength+"/"+totalLength);
                        viewHolderBar.textSpeed.setText(speed);
                        viewHolderBar.progress.setProgress((int) (progres.fraction * 100000));//下载条
                    }
                });
    }

    /**
     * 跳转APK安装
     *
     * @param context 上下文
     * @param name    下载名字
     */
    public void installApk(Context context, String name) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        String type = "application/vnd.android.package-archive";
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(context, ".MyFileProvider", getApkFile(name));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(getApkFile(name));
        }
        intent.setDataAndType(uri, type);
        context.startActivity(intent);
    }

    /**
     * APK本地地址
     *
     * @param apkName 下载名字
     */
    public File getApkFile(String apkName) {
        String apkDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
                + "download" + File.separator;
        File newApkFile = new File(apkDir, apkName);       //File()的第一个参数为文件的父路径
        return newApkFile;
    }

    public class ViewHolderBar {
        public View rootView;
        public ProgressBar progress;
        public TextView textSize;
        public TextView textSpeed;

        public ViewHolderBar(View rootView) {
            this.rootView = rootView;
            this.progress = (ProgressBar) rootView.findViewById(R.id.progress);
            this.textSize = (TextView) rootView.findViewById(R.id.textSize);
            this.textSpeed = (TextView) rootView.findViewById(R.id.textSpeed);
        }

    }
}
